package com.lydms.service.impl;

import com.lydms.service.WordExcelService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.stereotype.Service;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class WordExcelServiceImpl implements WordExcelService {
    private static final Logger logger = LogManager.getLogger(WordExcelServiceImpl.class);

    /**
     * 获取指定地址的Excel表格中的数据
     *
     * @return
     * @throws Exception
     */
    @Override
    public List getLocalExcel() throws Exception {
//        文件的绝对地址
        String filePath = "D:\\template.xls";

        FileInputStream fileInputStream = new FileInputStream(filePath);
        BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
        POIFSFileSystem fileSystem = new POIFSFileSystem(bufferedInputStream);
        HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);
        HSSFSheet sheet = workbook.getSheet("Sheet1");

        int lastRowIndex = sheet.getLastRowNum();
        logger.info("数据的条数为:{}",lastRowIndex);
        ArrayList<HashMap> list = new ArrayList<>();
        for (int i = 1; i <= lastRowIndex; i++) {
            HSSFRow row = sheet.getRow(i);
            if (row == null) {
                break;
            }

//            对数据进行封装
            HashMap<String, String> map = new HashMap<>();
            for (int j = 0; j < 3; j++) {
                row.getCell(j).setCellType(Cell.CELL_TYPE_STRING);
                String cellValue = row.getCell(j).getStringCellValue();
                System.out.println(cellValue);
                switch (j) {
                    case 0:
                        map.put("english", cellValue);
                        break;
                    case 1:
                        map.put("chinese", cellValue);
                        break;
                    case 2:
                        map.put("codechinese", cellValue);
                        break;
                    default:
                        break;
                }
            }
            list.add(map);
        }

        bufferedInputStream.close();
        logger.info("从EXCEL表格中取出的数据为:{}", list.toString());
        return list;
    }
}
